<template>
	<page-wraper :safeAreaInsetBottom="false">
		<view title="地址信息" class="custom-card">
			<wd-steps :active="1" vertical>
				<wd-step>
					<template v-slot:icon>
						<view
							style="margin: 0 auto; width: 20px; height: 20px; background-color: #fff; color: #000; display: flex; align-items: center; justify-content: center; border-radius: 50%; border: 2px solid #000; margin-top: 5px;">
							<span style="color: #000; font-size: 13px;">寄</span>
						</view>
					</template>
					<template v-slot:title>
						<wd-button type="text" @click="() => chooseAddress(1)" style="color: black;">
							<template v-if="model.shipper_address.id">
								<b style="display: inline-block;">{{ model.shipper_address.name }}</b>
								{{ model.shipper_address.phone_number }}
							</template>
							<template v-else>
								<view style="display: inline; color: var(--wot-button-primary-bg-color, var(--wot-color-theme, #4d80f0)); font-size: 12px;">请选择寄件地址</view>
							</template>
						</wd-button>
					</template>
					<template v-slot:description v-if="model.shipper_address.id">
						<template v-if="model.shipper_address.country_code === 'CN'">
							{{ model.shipper_address.state_code }} {{ model.shipper_address.city }} {{
								model.shipper_address.address1 }} {{ model.shipper_address.address2 }}
						</template>
						<template v-else>
							{{ model.shipper_address.address1 }}
							<view v-if="model.shipper_address.address2">
								{{ model.shipper_address.address2 }}
							</view>
							<view>
								{{ model.shipper_address.city }}, {{ model.shipper_address.state_code }}, {{
									model.shipper_address.postal_code }} ({{ model.shipper_address.country_code }})
							</view>
						</template>
					</template>
				</wd-step>
				<wd-step>
					<template v-slot:icon>
						<view
							style="margin: 0 auto; width: 20px; height: 20px; background-color: #fff; color: #000; display: flex; align-items: center; justify-content: center; border-radius: 50%; border: 2px solid orange; margin-top: 5px;">
							<span style="color: orange; font-size: 13px;">收</span>
						</view>
					</template>
					<template v-slot:title>
						<wd-button type="text" @click="() => chooseAddress(2)" style="color: black;">
							<template v-if="model.address.id">
								<b style="display: inline-block;">{{ model.address.name }}</b>
								{{ model.address.phone_number }}
							</template>
							<template v-else>
								<view style="display: inline; color: var(--wot-button-primary-bg-color, var(--wot-color-theme, #4d80f0)); font-size: 12px;">请选择收件地址</view>
							</template>
						</wd-button>
					</template>
					<template v-slot:description v-if="model.address.id">
						<template v-if="model.address.country_code === 'CN'">
							{{ model.address.state_code }} {{ model.address.city }} {{ model.address.address1 }} {{
								model.address.address2 }}
						</template>
						<template v-else>
							{{ model.address.address1 }}
							<view v-if="model.address.address2">
								{{ model.address.address2 }}
							</view>
							<view>
								{{ model.address.city }}, {{ model.address.state_code }}, {{ model.address.postal_code
								}} ({{ model.address.country_code }})
							</view>
						</template>
					</template>
				</wd-step>
			</wd-steps>
		</view>

		<view class="custom-card">
			<wd-cell-group>
				<wd-picker label="订单类型" v-model="model.order_type" :columns="order_types" />
				<wd-picker label="取件方式" v-model="model.collect_type" :columns="collect_types" />
				<wd-calendar label="取件日期" type="date" v-model="model.ship_date" :min-date="Date.now()"
					v-if="model.collect_type == 1" />
				<wd-picker label="取件时间" v-model="model.ship_time" :columns="calcTimeRanges"
					v-if="model.collect_type == 1" />
				<wd-cell size="large" title="包裹信息" is-link clickable @click="editPackages">
					{{ model.packages.length }} 件
				</wd-cell>
				<wd-cell size="large" title="清关信息" is-link clickable @click="editItems">
					{{ model.items.length }} 项
				</wd-cell>
			</wd-cell-group>
		</view>

		<view class="custom-card" style="padding-bottom: 12px;">
			<view style="margin-bottom: 10px;">
				<wd-checkbox v-model="order_proto_allowed" shape="square">
					<view
						style="display: inline; color: var(--wot-button-primary-bg-color, var(--wot-color-theme, #4d80f0)); font-size: 12px;"
						@click="() => openProtocol(0)">订单条款</view>
				</wd-checkbox>

				<wd-checkbox v-model="payment_proto_allowed" shape="square">
					<view
						style="display: inline; color: var(--wot-button-primary-bg-color, var(--wot-color-theme, #4d80f0)); font-size: 12px;"
						@click="() => openProtocol(1)">支付结算条款</view>
				</wd-checkbox>
			</view>
			
			<wd-picker label="优惠券" v-model="model.coupon_id" :columns="coupons" />

			<wd-button type="primary" size="large" block :disabled="amount == 0 || model.items.length == 0"
				@click="submit">
				<template v-if="amount == 0 && model.packages.length > 0">
					包裹超出限制
				</template>
				<template v-else>
					提交订单 ({{ amount }} USD)
				</template>
			</wd-button>
		</view>

		<wd-popup v-model="tips_visible" position="bottom" :close-on-click-modal="false"
			custom-style="height: 400px; padding: 10px;">
			<div v-html="tips_content" style="height: 360px; overflow: scroll;"></div>

			<view style="text-align: center; margin-top: 10px;">
				<wd-button type="primary" block :disabled="tips_tick > 0" @click="() => tips_visible = false">
					<template v-if="tips_tick > 0">
						同意 （{{ tips_tick }}s）
					</template>
					<template v-else>
						同意
					</template>
				</wd-button>
			</view>
		</wd-popup>
		
		<wd-popup v-model="pay_visible" position="bottom" closable :z-index="9999" @close="cancelPay" :close-on-click-modal="false"
			custom-style="height: 300px; padding-top: 10px;">
			<view style="text-align: center; font-size: 14px;">
				选择支付方式
			</view>
			<demo-block title="" transparent>
				<wd-cell-group>
					<wd-cell size="large" is-link :to="`/pages/pay/Index?id=${pay_order_id}`" title="AsiaPay">
						<view style="font-size: 12px;">
							跳转第三方支付
						</view>
						<template #icon>
							<view class="cell-icon" style="background-image: url(https://www.ytad-pep.com/asiapay.png)"></view>
						</template>
					</wd-cell>
					<wd-cell size="large" is-link>
						<view style="color: gray; font-size: 12px;">
							暂未开通
						</view>
						<template #title>
							<view style="color: gray;">
								微信支付
							</view>
						</template>
						<template #icon>
							<view class="cell-icon" style="background-image: url(https://www.ytad-pep.com/wxpay.png);filter:brightness(0);opacity: 50%;"></view>
						</template>
					</wd-cell>
				</wd-cell-group>
			</demo-block>
		</wd-popup>
	</page-wraper>
</template>

<script lang="ts" setup>
import { ref, onUnmounted, computed, watch } from 'vue'

	const protocols = [
		['订单条款', 'order_proto_content'],
		['支付结算条款', 'payment_proto_content']
	];
	const model = ref({
		shipper_address: ref<any>({}),
		address: ref<any>({}),
		order_type: '',
		collect_type: 0,
		ship_date: ref<any>(Date.now()),
		ship_time: 1,
		packages: ref<any>([]),
		items: ref<any>([]),
		ship_method_id: 0,
		coupon_id: 0
	});
	const order_proto_allowed = ref(false);
	const payment_proto_allowed = ref(false);
	const amount = ref(0);
	const rateTimer = ref<any>(0);
	const tips_visible = ref(false);
	const tips_content = ref('');
	const tips_tick = ref(10);
	const pay_visible = ref(false);
	const pay_order_id = ref('');

	const order_types = ref([
		{
			value: '',
			label: '请选择'
		},
		{
			value: 'OLD',
			label: '旧行李物品'
		},
		{
			value: 'NEW',
			label: '全新物品'
		}
	])
	const collect_types = ref([
		{
			value: 0,
			label: '请选择'
		},
		{
			value: 1,
			label: '预约免费上门取件'
		},
		{
			value: 2,
			label: '自行到门店投递'
		}
	])

	const timeRanges = ref([
		{ value: 1, label: '上午 09:00-12:00' },
		{ value: 2, label: '下午 14:00-18:00' }
	]);
	
	const coupons = ref([]);

	const calcTimeRanges = computed(() => {
		if (new Date(model.value.ship_date).toDateString() === new Date().toDateString()) {
			if (new Date().getHours() >= 17) {
				return [];
			} else if (new Date().getHours() >= 11) {
				return [timeRanges.value[1]];
			}
		}

		return timeRanges.value;
	});
	
	watch(() => model.value.order_type, () => {
		rates();
	})
	watch(() => model.value.coupon_id, () => {
		rates();
	})
	
	uni.$http.get('/user/coupon/list?status=2&page=1&limit=100').then(res => {
		if (res.data.code == 0 && res.data.data.length > 0) {
			coupons.value.push({ value: 0, label: '选择优惠券' });
			res.data.data.forEach(a => {
				coupons.value.push({ value: a.id, label: a.name, price: a.price });
			});
		}
	});

	uni.$http.get('/system_config/content/order_tips').then(res => {
		if (res.data.code == 0) {
			tips_content.value = res.data.data;
			tips_visible.value = true;
			tips_tick.value = 5;

			let timer = setInterval(() => {
				tips_tick.value--;

				if (tips_tick.value <= 0) {
					clearInterval(timer);
				}
			}, 1000);
		}
	});

	function chooseAddress(type : Number) {
		uni.setStorageSync('type', type);

		uni.navigateTo({
			url: '/pages/address_book/Choose'
		});
	}

	function editPackages() {
		uni.navigateTo({
			url: `/pages/order/Package?orderType=${model.value.order_type}&packages=${encodeURIComponent(JSON.stringify(model.value.packages))}`,
		});
	}

	function editItems() {
		uni.navigateTo({
			url: `/pages/order/Item?orderType=${model.value.order_type}&items=${encodeURIComponent(JSON.stringify(model.value.items))}&packages=${encodeURIComponent(JSON.stringify(model.value.packages))}`
		});
	}
	
	function cancelPay() {
		uni.redirectTo({ url: '/pages/order/Index' });
	}

	function rates() {
		clearTimeout(rateTimer.value);
		
		if (model.value.collect_type == 0 || model.value.order_type == '') {
			return;
		}

		rateTimer.value = setTimeout(() => {
			uni.$http.post('user/order/rates', model.value).then(res => {
				amount.value = 0;
				
				if (res.data.code == 0) {
					model.value.ship_method_id = res.data.data.ship_method_id;
					amount.value = res.data.data.ship_methods[0].amount;
				}
			});
		}, 300);
	}

	function submit() {
		if (!order_proto_allowed.value || !payment_proto_allowed.value) {
			uni.showToast({
				title: '请先同意协议',
				icon: 'none'
			});

			return;
		}

		uni.showLoading({
			title: '您的运单已提交，标签和发票系统制作中，请耐心等待！'
		});

		const data = Object.assign({}, model.value);

		data.ship_date = new Date(data.ship_date).toISOString().slice(0, 19).replace('T', ' ')

		uni.$http.post('user/order/submit', data).then(res => {
			uni.hideLoading();

			if (res.data.code == 0) {
				uni.showToast({
					title: '订单提交成功',
					icon: 'success',
					complete: () => {
						/*#ifdef MP-WEIXIN*/
						pay_visible.value = true;
						pay_order_id.value = res.data.data.id;
						/*#endif*/

						/*#ifdef H5*/
						uni.$http.get(`user/order/payment_params/uni/${res.data.data.id}`).then(res => {
							const form = document.createElement('form');
							form.method = 'POST';
							form.action = res.data.data.url;

							for (const key in res.data.data.forms) {
								const input = document.createElement('input');
								input.type = 'hidden';
								input.name = key;
								input.value = res.data.data.forms[key];
								form.appendChild(input);
							}

							document.body.appendChild(form);

							form.submit();
						});
						/*#endif*/
					}
				});
			} else {
				uni.showToast({
					title: res.data.msg,
					icon: 'error'
				});
			}
		});
	}

	function openProtocol(index : number) {
		uni.navigateTo({ url: `/pages/protocol/Index?type=${protocols[index][1]}&title=${protocols[index][0]}` });
	}

	uni.$on('chooseAddress', (data) => {
		if (data.type == 1) {
			model.value.shipper_address = data.row;
		} else {
			model.value.address = data.row;
		}

		rates();
	});

	uni.$on('changePackages', (data) => {
		model.value.packages = data;
		
		for (var i = 0; i < model.value.items.length; i++) {
			const item = model.value.items[i];
			
			if (!model.value.packages.find(a => a.id == item.package_id)) {
				model.value.items.splice(i--, 1)
			}
		}

		rates();
	});

	uni.$on('changeItems', (data) => {
		model.value.items = data;
	});

	onUnmounted(() => {
		uni.$off('chooseAddress');
		uni.$off('changePackages');
		uni.$off('changeItems');
	});
</script>

<style lang="scss" scoped>
	:deep(.page-wraper) {
		background: #f6f6f6;
	}

	:deep(.wd-calendar__value),
	:deep(.wd-picker__value) {
		text-align: right;
	}

	:deep(.wd-calendar__label),
	:deep(.wd-picker__label) {
		font-size: var(--wot-cell-title-fs-large, 16px);
	}

	.custom-card {
		padding: var(--wot-card-padding, 0 var(--wot-size-side-padding, 15px));
		background-color: var(--wot-card-bg, var(--wot-color-white, rgb(255, 255, 255)));
		line-height: var(--wot-card-line-height, 1.1);
		margin: var(--wot-card-margin, 0 var(--wot-size-side-padding, 15px));
		border-radius: var(--wot-card-radius, 8px);
		box-shadow: var(--wot-card-shadow-color, 0px 4px 8px 0px rgba(0, 0, 0, 0.02));
		font-size: var(--wot-card-fs, var(--wot-fs-content, 14px));
		margin-bottom: 12px;
		padding-top: 12px;
		margin-top: 12px;
	}

	.cell-icon {
		display: block;
		box-sizing: border-box;
		width: 24px;
		height: 24px;
		margin-right: 4px;
		background-repeat: no-repeat;
		background-size: cover;
	}
</style>